#include<iostream>
using namespace std;
#include<unordered_map>
#include<string>
#include<algorithm>

//采用位运算，每次取四个比特位进行映射
class Solution {
public:
    string toHex(int num) {
        if (num == 0) return string("0");
        unordered_map<unsigned int, string> Dec2Hex;

        for (int i = 0; i < 16; ++i) {
            if (i < 10) Dec2Hex.insert({ i, string(1, '0' + i)});
            else Dec2Hex.insert({ i, string(1, 'a' + i - 10)});
        }

        string ret;
        unsigned int x = 15;
        //对补码进行运算即可 num是一个有符号整形 
        //且一切运算都是对补码进行运算

        int movei = 0;
        while(movei <= 7){
            unsigned int MatchNum_Per4bit = (x << (movei * 4)) & num;
            MatchNum_Per4bit = MatchNum_Per4bit >> (movei * 4);
            ret += Dec2Hex[MatchNum_Per4bit];
            ++movei;
        }
        reverse(ret.begin(), ret.end());
        //清除所有的前置0即可
        int i = 0;
        for(i = 0; i < ret.size(); ++i)
            if(ret[i] != '0') break;
        return string(ret.begin() + i, ret.end());   
    }
};
